import json
import socket

import config
from flask import Flask, request, render_template

####################################################################################################

app = Flask(__name__)


####################################################################################################

@app.route('/')
def index():
    return render_template('index.html')


def _add_4space(content_split):
    '''
    行首加4个空格
    :param content_split:
    :return:
    '''
    ret_str = ''

    for s in content_split:
        ret_str += '\t' + s + '\n'

    return ret_str


@app.route('/do_process', methods=['POST', 'GET'])
def do_process():
    if request.method == 'POST':

        json_data = None
        for v in request.values.keys():
            json_data = json.loads(v)
            break
        if json_data == None:
            return json.dumps({'ret_str': 'ERROR'})

        # list_data = [(key,value) for key,value in json_data.items()]
        # list_data.sort(key=lambda x:x[0])
        # for data in list_data:
        # ret_str += '【%s】\n%s\n\n' % (data[1]['title'], data[1]['content'])

        route = json_data['route']

        content1 = json_data['content1']
        content2 = json_data['content2']
        content3 = json_data['content3']

        content11 = json_data['content11']
        content12 = json_data['content12']
        content13 = json_data['content13']
        content14 = json_data['content14']

        content21 = json_data['content21']
        content22 = json_data['content22']

        content31 = json_data['content31']
        content32 = json_data['content32']
        content33 = json_data['content33']
        content34 = json_data['content34']

        content1_split = content1['content'].split('\n')
        content2_split = content2['content'].split('\n')
        content3_split = content3['content'].split('\n')

        content11_split = content11['content'].split('\n')
        content12_split = content12['content'].split('\n')
        content13_split = content13['content'].split('\n')
        content14_split = content14['content'].split('\n')

        content21_split = content21['content'].split('\n')
        content22_split = content22['content'].split('\n')

        content31_split = content31['content'].split('\n')
        content32_split = content32['content'].split('\n')
        content33_split = content33['content'].split('\n')
        content34_split = content34['content'].split('\n')

        ret_str = content1_split[0] \
                  + '（标题）' + '\n\n' \
 \
                  + '天气：' + content1_split[1] + '\n' \
                  + '地点：' + content1_split[2] + '\n' \
                  + '人物：' + content13_split[0] + '\n\n' \
 \
                  + route['content'] + '\n\n' \
 \
                  + content2['title'] + '\n' + _add_4space(content2_split) + '\n' \
                  + content3['title'] + '\n' + _add_4space(content3_split) + '\n' \
 \
                  + content11['title'] + '\n' + _add_4space(content11_split) + '\n' \
                  + content12['title'] + '\n' + _add_4space(content12_split) + '\n' \
                  + content13['title'] + '\n' + _add_4space(content13_split[1:]) + '\n' \
                  + content14['title'] + '\n' + _add_4space(content14_split) + '\n' \
 \
                  + content21['title'] + '\n' + _add_4space(content21_split) + '\n' \
                  + content22['title'] + '\n' + _add_4space(content22_split) + '\n' \
 \
                  + content31['title'] + '\n' + _add_4space(content31_split) + '\n' \
                  + content32['title'] + '\n' + _add_4space(content32_split) + '\n' \
                  + content33['title'] + '\n' + _add_4space(content33_split) + '\n' \
                  + content34['title'] + '\n' + _add_4space(content34_split)

        return json.dumps({'ret_str': ret_str})

    return 'invalid operation!'


def _writeFile(filePath, content):
    with open(filePath, 'w') as f:
        f.write('%s' % content)


def _init():
    '''
    初始化
    :return:
    '''
    # ip
    config.CONFIG['ip'] = socket.gethostbyname(socket.gethostname())
    _writeFile('IP.cfg', config.CONFIG['ip'])

    # port
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    for port in range(config.CONFIG['port'], 10000):
        try:
            s.connect((config.CONFIG['ip'], port))
            s.shutdown(2)
            continue
        except:
            config.CONFIG['port'] = port
            _writeFile('PORT.cfg', config.CONFIG['port'])
            break


if __name__ == '__main__':
    _init()

    # 网页
    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

    app.run(
        host=config.CONFIG['ip'],
        port=config.CONFIG['port'],
        debug=config.CONFIG['debug'],
        threaded=True
    )
